package com.utils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.las.common.Constant;
import com.las.config.AppConfigs;
import com.las.dto.CqResponse;
import com.las.utils.JsonUtils;
import com.las.utils.mirai.HttpUtil;
import com.las.utils.mirai.MiRaiUtil;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;

public class BotUtils {

    private static Logger logger = Logger.getLogger(BotUtils.class);

    private static String baseURL = AppConfigs.miRaiApiUrl;

    public static void sendCusMsg(Long userId, Long id, int type, List<JSONObject> msgList) {
        switch(type) {
            case 0:
                MiRaiUtil.getInstance().sendMsg(userId, id, msgList, "private");
                break;
            case 1:
                MiRaiUtil.getInstance().sendMsg(userId, id, msgList, "group");
                break;
            case 2:
                MiRaiUtil.getInstance().sendMsg(userId, id, msgList, "discuss");
                break;
        }
    }

    /**
     * CQ发送语音消息
     *
     * @param url    网络图URL
     * @param userId  用户ID
     * @param id      组ID
     * @param type    消息类型
     */
    public static CqResponse sendVoiceMessage(String url, Long userId, Long id, int type) {
        CqResponse response = null;
        switch (type) {
            case Constant.MESSAGE_TYPE_PRIVATE:
                response = sendVoiceMsg(userId, id, url, "private");
                break;
            case Constant.MESSAGE_TYPE_GROUP:
                response = sendVoiceMsg(userId, id, url, "group");
                break;
            case Constant.MESSAGE_TYPE_DISCUSS:
                response = sendVoiceMsg(userId, id, url, "discuss");
                break;
            default:
                break;
        }
        return response;
    }


    private static CqResponse sendVoiceMsg(Long id, Long gId, String url, String type) {
        //音频的发送，私聊发似乎不行了，查API 腾讯那边也没有文档
        File file = null;
        try {
            String URL;
            String fileName = UUID.randomUUID().toString();
            BufferedInputStream bis = new BufferedInputStream(Objects.requireNonNull(HttpUtil.getFileInputStream(url)));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
            int b;
            while (-1 != (b = bis.read())) {
                bos.write(b);
            }
            bos.close();
            bis.close();

            ArrayList<JSONObject> msgList = new ArrayList<>();
            file = new File(fileName);
            String base64File = FileBase64Utils.encodeBase64File(file.getAbsolutePath());

            JSONObject object = new JSONObject();
            object.put("type", "Record");
            object.put("file", base64File);
            msgList.add(object);


            Map<String, Object> info3 = new HashMap<>();
            switch (type) {
                case "group":
                    URL = baseURL + "/sendGroupMessage";
                    info3.put("sessionKey", Constant.session);
                    info3.put("target", gId);
                    info3.put("messageChain", msgList);

                    break;
                case "discuss":
                    URL = baseURL + "/sendTempMessage";
                    info3.put("sessionKey", Constant.session);
                    info3.put("qq", id);
                    info3.put("group", gId);
                    info3.put("messageChain", msgList);
                    break;
                case "private":
                    URL = baseURL + "/sendFriendMessage";
                    info3.put("sessionKey", Constant.session);
                    info3.put("target", id);
                    info3.put("messageChain", msgList);
                    break;
                default:
                    return null;
            }

            String result = null;
            try {
                result = HttpKit.post(URL, com.las.utils.JsonUtils.getJsonString(info3));
                logger.debug("CQ发送消息返回结果：" + result);
            } catch (Exception e) {
                logger.error("CQ发送异常：" + e.toString(), e);
            }
            if (result == null) {
                //可能发群消息有风控！如果拿不到消息ID，开启临时会话，私聊发给用户
                if ("group".equals(type)) {
                    Map<String, Object> info4 = new HashMap<>();
                    info4.put("sessionKey", Constant.session);
                    info4.put("qq", id);
                    info4.put("group", gId);
                    info4.put("messageChain", msgList);
                    String result2 = HttpKit.post(baseURL + "/sendTempMessage", JsonUtils.getJsonString(info4));
                    logger.info("CQ结果2：" + result2);
                }
            }
        } catch (Exception ignored) {

        } finally {
            //最后删除文件
            if (null != file) {
                file.delete();
            }
        }
        return null;

    }

}
